'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import styled from 'styled-components';
import CesiumMap from './components/CesiumMap';
import DroneMonitoring from './components/DroneMonitoring';
import AirspaceStats from './components/AirspaceStats';
import DeviceStatus from './components/DeviceStatus';
import AlertsPanel from './components/AlertsPanel';
import FlightPlans from './components/FlightPlans';
import DataCharts from './components/DataCharts';
import TrajectoryButton from './components/TrajectoryButton';

// 科技感顶部导航栏
const TechHeader = styled.header`
  width: 100%;
  height: 80px;
  background-image: url('/images/dashboard/headers/main-header.png');
  background-size: 100% auto;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  position: relative;
  background-color: rgba(0, 21, 41, 0.7);
  backdrop-filter: blur(10px);
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.5), inset 0 0 10px rgba(24, 144, 255, 0.3);
  border-bottom: 1px solid rgba(24, 144, 255, 0.3);
  
  &::before {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
    height: 1px;
    background: linear-gradient(90deg, transparent, rgba(24, 144, 255, 0.8), transparent);
  }
  
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, rgba(24, 144, 255, 0.5), transparent);
  }
`;

// 左侧天气和时间信息 - 更新为只有时间信息
const TimeInfo = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 5px;
  min-width: 180px;
`;

// 时间显示
const TimeDisplay = styled.div`
  color: white;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
`;

// 右侧用户信息和退出按钮
const UserActions = styled.div`
  display: flex;
  align-items: center;
  min-width: 180px;
  justify-content: flex-end;
`;

// 用户信息
const UserInfo = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  color: #a0cfff;
  font-size: 14px;
  position: relative;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.3s;
  
  .user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: rgba(24, 144, 255, 0.3);
    border: 1px solid rgba(24, 144, 255, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
  }
  
  &:hover {
    background-color: rgba(24, 144, 255, 0.2);
  }
`;

// 退出系统提示气泡
const ExitTooltip = styled.div`
  position: absolute;
  top: 100%;
  left: 0;
  background-color: rgba(0, 21, 41, 0.9);
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 8px;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(24, 144, 255, 0.5);
  z-index: 99999;
  cursor: pointer;
  
  &::before {
    content: '';
    position: absolute;
    bottom: 100%;
    left: 15px;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-bottom: 6px solid rgba(0, 21, 41, 0.9);
  }
  
  &:hover {
    background-color: rgba(24, 144, 255, 0.2);
  }
`;

// 头部中间部分容器
const HeaderCenter = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
`;

// 导航按钮容器，向中间靠拢
const NavButtons = styled.div`
  display: flex;
  gap: 15px;
  height: 100%;
  align-items: center;
  position: relative;
  margin: 0 60px;
`;

// 系统标题容器
const TitleContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  position: relative;
  
  &::before, &::after {
    content: '';
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 100px;
    height: 2px;
    background: linear-gradient(90deg, transparent, rgba(24, 144, 255, 0.8), transparent);
  }
  
`;

// 系统标题
const SystemTitle = styled.div`
  font-size: 26px;
  color: white;
  text-align: center;
  font-weight: bold;
  //text-shadow: 0 0 10px rgba(24, 144, 255, 0.8);
  background: linear-gradient(180deg, #ffffff, #a0cfff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 3px;
  position: relative;
  margin-bottom: 5px;
  
  &::before, &::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 30px;
    height: 1px;
    background: linear-gradient(90deg, transparent, #1890ff);
  }
  
  &::before {
    right: calc(100% + 15px);
  }
  
  &::after {
    left: calc(100% + 15px);
    transform: rotate(180deg);
  }
`;

// 系统副标题
const SystemSubtitle = styled.div`
  font-size: 12px;
  color: rgba(160, 207, 255, 0.8);
  letter-spacing: 2px;
  text-transform: uppercase;
  position: relative;
  
  &::before, &::after {
    content: '●';
    font-size: 6px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    color: #1890ff;
  }
  
  &::before {
    left: -15px;
  }
  
  &::after {
    right: -15px;
  }
`;

// 科技感导航按钮
const NavButton = styled.div`
  background-image: url('/images/dashboard/buttons/nav-buttons.png');
  background-size: 100% 100%;
  width: 140px;
  height: 45px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #a0cfff;
  cursor: pointer;
  font-size: 14px;
  font-family: "Microsoft YaHei", sans-serif;
  font-weight: 500;
  letter-spacing: 1px;
  text-shadow: 0 0 5px rgba(24, 144, 255, 0.5);
  position: relative;
  
  &[data-active="true"] {
    color: #ffffff;
  }
  
  &::before, &::after {
    content: '';
    position: absolute;
    bottom: -5px;
    height: 2px;
    background: #1890ff;
    opacity: 0;
    transition: all 0.3s;
  }
  
  &::before {
    left: 20%;
    width: 30%;
  }
  
  &::after {
    right: 20%;
    width: 30%;
  }
  
  &[data-active="true"]::before, &[data-active="true"]::after {
    opacity: 1;
  }
  
  &:hover::before, &:hover::after {
    opacity: 0.5;
  }
  
  &:hover {
    color: #ffffff;
  }
`;

// 主容器
const DashboardContainer = styled.div`
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  color: white;
  position: relative;
`;

// 地图容器
const MapContainer = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 1;
  overflow: hidden;
`;

// 遮罩层 - 在地图和UI层之间
const OverlayMask = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('/images/dashboard/backgrounds/main-bg.png');
  background-size: cover;
  pointer-events: none;
  z-index: 5;
  //box-shadow: inset 0 0 150px 50px rgba(0, 8, 20, 0.9);
  mix-blend-mode: multiply;
  opacity: 0.5;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(
      ellipse at center,
      rgba(0, 0, 0, 0) 30%,
      rgba(0, 21, 41, 0.7) 100%
    );
    pointer-events: none;
  }
  
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-shadow: inset 0 0 200px 100px rgba(0, 8, 20, 0.8);
    pointer-events: none;
  }
`;

// 顶部导航栏容器
const HeaderContainer = styled.div`
  position: relative;
  z-index: 10;
`;

// 主内容区
const MainContent = styled.div`
  display: flex;
  flex: 1;
  overflow: hidden;
  padding: 10px;
  gap: 10px;
  position: relative;
  z-index: 10;
  height: calc(100vh - 80px);
  justify-content: space-between;
  pointer-events: none;
`;

// 左侧面板
const LeftPanel = styled.div`
  width: 22%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  pointer-events: auto;
`;

// 空白中间区域
const CenterArea = styled.div`
  flex: 1;
  min-width: 30px;
  pointer-events: none;
`;

// 右侧面板
const RightPanel = styled.div`
  width: 22%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  pointer-events: auto;
`;

// 数据面板标题
const PanelTitle = styled.div`
  display: flex;
  align-items: center;
  color: white;
  font-size: 16px;
  margin-bottom: 10px;
  background-image: url('/images/dashboard/borders/title-bg.png');
  background-size: contain;
  background-repeat: no-repeat;
  height: 32px;
  padding-left: 36px;
  padding-bottom: 5px;
  position: relative;
  font-weight: 500;
  letter-spacing: 1px;
  text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
`;

// 科技感面板容器
const TechPanel = styled.div`
  background-image: url('/images/dashboard/borders/panel-border.png');
  background-size: 100% 100%;
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(5px);
  background-color: rgba(0, 21, 41, 0.6);
  border: 1px solid rgba(24, 144, 255, 0.5);
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  pointer-events: auto;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, #1890ff, transparent);
  }
`;

const DashboardPage = () => {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [activeNav, setActiveNav] = useState('airspace');
  const [currentTime, setCurrentTime] = useState('');
  const [currentDate, setCurrentDate] = useState('');
  const [showUserTooltip, setShowUserTooltip] = useState(false);
  const user = { name: '管理员', avatar: 'A' };

  useEffect(() => {
    // 确保在客户端环境中执行localStorage操作
    if (typeof window !== 'undefined') {
      // 检查用户是否已登录
      const userInfo = localStorage.getItem('user');
      if (!userInfo) {
        router.push('/login');
        return;
      }
      setLoading(false);
    }
  }, [router]);

  const handleNavClick = (nav: string) => {
    setActiveNav(nav);
    // 这里可以添加路由导航逻辑
  };

  const handleUserClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setShowUserTooltip(!showUserTooltip);
  };

  // 添加全局点击事件处理器，点击页面任何其他位置关闭提示气泡
  useEffect(() => {
    const handleGlobalClick = () => {
      if (showUserTooltip) {
        setShowUserTooltip(false);
      }
    };
    
    document.addEventListener('click', handleGlobalClick);
    
    return () => {
      document.removeEventListener('click', handleGlobalClick);
    };
  }, [showUserTooltip]);

  // 处理退出系统的点击事件
  const handleExitSystem = (e: React.MouseEvent) => {
    e.stopPropagation();
    console.log('退出大屏显示');
    // 示例跳转到登录页
    router.push('/login');
    // 或者使用 window.location.href = '/login';
  };

  useEffect(() => {
    const updateTime = () => {
      const now = new Date();
      const timeString = now.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
      const dateString = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        weekday: 'short'
      });
      
      setCurrentTime(timeString);
      setCurrentDate(dateString);
    };
    
    // 立即更新一次
    updateTime();
    
    // 设置定时器，每秒更新
    const timer = setInterval(updateTime, 1000);
    
    // 清除定时器
    return () => clearInterval(timer);
  }, []);

  if (loading) {
    return (
      <DashboardContainer>
        <div className="flex items-center justify-center h-full">
          <p>加载中...</p>
        </div>
      </DashboardContainer>
    );
  }

  return (
    <DashboardContainer>
      {/* 地图作为底图 */}
      <MapContainer>
        <CesiumMap />
      </MapContainer>
      
      {/* 遮罩层 - 四周阴影效果 */}
      <OverlayMask />
      
      {/* 顶部导航 */}
      <HeaderContainer>
        <TechHeader>
          {/* 左侧时间信息 */}
          <TimeInfo>
            <TimeDisplay>
              <div>{currentTime}</div>
              <div style={{ fontSize: '12px', opacity: 0.8 }}>{currentDate}</div>
            </TimeDisplay>
          </TimeInfo>
          
          {/* 中间部分 */}
          <HeaderCenter>
            {/* 左侧导航按钮 */}
            <NavButtons>
              <NavButton 
                data-active={(activeNav === 'airspace').toString()} 
                onClick={() => handleNavClick('airspace')}
              >
                低空管控
              </NavButton>
              <NavButton 
                data-active={(activeNav === 'flights').toString()} 
                onClick={() => handleNavClick('flights')}
              >
                低空政务
              </NavButton>
            </NavButtons>
            
            {/* 标题 */}
            <TitleContainer>
              <SystemTitle>
                江门市空域链低空智能管理系统
              </SystemTitle>
              <SystemSubtitle>Jiangmen airspace chain low-altitude intelligent management system</SystemSubtitle>
            </TitleContainer>
            
            {/* 右侧导航按钮 */}
            <NavButtons>
              <NavButton 
                data-active={(activeNav === 'dashboard').toString()} 
                onClick={() => handleNavClick('dashboard')}
              >
                低空航线
              </NavButton>
              <NavButton 
                data-active={(activeNav === 'analysis').toString()} 
                onClick={() => handleNavClick('analysis')}
              >
                低空物流
              </NavButton>
            </NavButtons>
          </HeaderCenter>
          
          {/* 右侧用户信息 */}
          <UserActions>
            <UserInfo data-show-tooltip={showUserTooltip.toString()} onClick={handleUserClick}>
              <div className="user-avatar">{user.avatar}</div>
              <span>{user.name}</span>
              {showUserTooltip && (
                <ExitTooltip onClick={handleExitSystem}>
                  退出系统
                </ExitTooltip>
              )}
            </UserInfo>
          </UserActions>
        </TechHeader>
      </HeaderContainer>
      
      {/* 历史轨迹监测按钮 */}
      <TrajectoryButton />
      
      {/* 主内容区域 */}
      <MainContent>
        <LeftPanel>
          <TechPanel style={{ flex: 1 }}>
            <PanelTitle>无人机监测</PanelTitle>
            <DroneMonitoring />
          </TechPanel>
          
          <TechPanel style={{ flex: 1 }}>
            <PanelTitle>数据统计</PanelTitle>
            <DataCharts />
          </TechPanel>
          
          <TechPanel style={{ flex: 1 }}>
            <PanelTitle>空域资源使用统计</PanelTitle>
            <AirspaceStats />
          </TechPanel>
        </LeftPanel>
        
        <CenterArea />
        
        <RightPanel>
          <TechPanel>
            <PanelTitle>设备状态</PanelTitle>
            <DeviceStatus />
          </TechPanel>
          
          <TechPanel>
            <PanelTitle>告警信息</PanelTitle>
            <AlertsPanel />
          </TechPanel>
          
          <TechPanel>
            <PanelTitle>飞行计划</PanelTitle>
            <FlightPlans />
          </TechPanel>
        </RightPanel>
      </MainContent>
    </DashboardContainer>
  );
}

export default DashboardPage; 